package com.sparrow.socket.http;

import com.sparrow.common.util.PropertiesUtil;
import com.sparrow.socket.http.api.HttpServer;
import com.sparrow.socket.http.handler.HttpIdleStateHandler;
import com.sparrow.socket.http.handler.HttpPacketHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
@ComponentScan("com.sparrow.socket.http")
public class SparrowHttpAutoConfig {
    @Bean
    public HttpPacketHandler httpPacketHandler() {
        return new HttpPacketHandler();
    }

    @Bean
    public HttpServer httpServer(HttpPacketHandler httpPacketHandler) {
        HttpServer httpServer = new HttpServer();
        httpServer.setChannelInitializer(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                // 添加 HTTP 编解码器
                pipeline.addLast(new HttpServerCodec());
                // 聚合 HTTP 消息，转换为 FullHttpRequest 最大长度65K
                pipeline.addLast(new HttpObjectAggregator(65536));
                // 添加自定义 RESTful 请求处理器
                pipeline.addLast(httpPacketHandler);
                //60 秒没收到消息就出发idle
                pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
                pipeline.addLast(new HttpIdleStateHandler());
            }
        });
        httpServer.start(Integer.valueOf(PropertiesUtil.getProperty("http.port")));
        return httpServer;
    }

}

